package cc.eddic.pratice.programmingparadigms.emp03objlist;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class ObjectList {
    private static final Logger log = LoggerFactory.getLogger(ObjectList.class);
    private Object[] data;
    private int index;

    protected ObjectList() {
        this(10);
    }

    protected ObjectList(int capacity) {
        data = new Object[capacity];
        index = 0;
    }

    protected void add(Object obj) {
        if (index == data.length) {
            Object[] objects = new Object[data.length * 2];
            System.arraycopy(data, 0, objects, 0, size());
            data = objects;
            data[index] = obj;
            index++;
            if (log.isDebugEnabled()) log.debug("超出数组长度，进行扩容长度为 {}！！", data.length);
        } else {
            data[index] = obj;
            index++;
        }
    }

    protected Object get(int index) {
        if (index < 0 || index >= size()) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
        }
        return data[index];
    }

    public int size() {
        return index;
    }


    protected void sort(ObjectComparator comparator) {
        // 冒泡排序
        for (int i = 0; i < size(); i++) {
            for (int j = 0; j < size() - i - 1; j++) {
                // 什么情况下要交换
                if (comparator.compare(data[j], data[j + 1]) > 0) {
                    // 交换
                    Object temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
            }
        }
    }

    protected Object find(ObjectPredicate predicate) {
        for (int i = 0; i < size(); ++i) {
            Object r = get(i);
            if (predicate.test(r)) {
                return r;
            }
        }
        return null;
    }

}
